<template>
  <el-card style="margin: 10px 0px">
    <el-form :inline="true" class="form">
      <el-form-item label="角色名称">
        <el-input v-model="roleName" placeholder="角色名称"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button
          @click="handleSearch"
          type="primary"
          :disabled="roleName ? false : true"
        >
          搜索
        </el-button>
        <el-button @click="reset">重置</el-button>
      </el-form-item>
    </el-form>
  </el-card>
  <el-card>
    <el-button type="primary" icon="Plus" @click="addRole">添加角色</el-button>
    <el-table :data="roleArr" border style="margin: 10px 0px">
      <el-table-column
        label="序号"
        type="index"
        align="center"
        width="80px"
      ></el-table-column>
      <el-table-column prop="id" label="id" align="center"></el-table-column>
      <el-table-column
        :show-overflow-tooltip="true"
        label="角色名称"
        align="center"
        prop="roleName"
      ></el-table-column>
      <el-table-column
        :show-overflow-tooltip="true"
        label="创建时间"
        align="center"
        prop="createTime"
      ></el-table-column>
      <el-table-column
        :show-overflow-tooltip="true"
        label="更新时间"
        align="center"
        prop="updateTime"
      ></el-table-column>
      <el-table-column width="300px" label="操作" align="center">
        <template #="{ row, $index }">
          <el-button
            @click="setPermission(row)"
            type="primary"
            icon="User"
            size="small"
            plain
          >
            分配权限
          </el-button>
          <el-button
            icon="Edit"
            type="success"
            size="small"
            plain
            @click="updateRole(row)"
          >
            编辑
          </el-button>
          <el-popconfirm
            @confirm="deleteRole(row.id)"
            :title="`您确定要删除${row.roleName}吗?`"
            width="220px"
          >
            <template #reference>
              <el-button icon="Delete" type="danger" size="small" plain>
                删除
              </el-button>
            </template>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页器 -->
    <el-pagination
      @current-change="getRoleInfo"
      @size-change="handler"
      v-model:current-page="currentPage"
      v-model:page-size="pageSize"
      :background="true"
      :page-sizes="[5, 7, 9, 11]"
      :total="total"
      layout="prev,pager,next,jumper,->,sizes,total"
    ></el-pagination>
  </el-card>
  <!-- 添加职位与更新已有职位的结构 -->
  <el-dialog
    v-model="dialogFormValue"
    :title="RoleParams.id ? '更新职位' : '添加职位'"
  >
    <el-form ref="form" :rules="rules" :model="RoleParams">
      <el-form-item prop="roleName" label="角色名称">
        <el-input
          v-model="RoleParams.roleName"
          placeholder="请您输入角色名称"
        ></el-input>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="dialogFormValue = false">取消</el-button>
      <el-button type="primary" @click="save">确定</el-button>
    </template>
  </el-dialog>
  <!-- 抽屉组件：分配用户的职位权限与按钮的权限 -->
  <el-drawer v-model="drawer">
    <template #header>
      <h4>分配菜单与按钮的权限</h4>
    </template>
    <template #default>
      <!-- 树形控件 -->
      <el-tree
        ref="tree"
        :props="defaultProps"
        :data="menuArr"
        show-checkbox
        node-key="id"
        :default-expanded-keys="[1]"
        :default-checked-keys="selectArr"
      ></el-tree>
    </template>
    <template #footer>
      <el-button @click="drawer = false">取消</el-button>
      <el-button type="primary" @click="selectHandler">确定</el-button>
    </template>
  </el-drawer>
</template>

<script setup lang="ts">
import { ref, onMounted, reactive, nextTick } from 'vue'
import {
  reqAllRoleList,
  reqAddOrUpdateRole,
  reqAllMenuList,
  reqSetPermission,
  reqRemoveRole,
} from '@/api/acl/role'
import {
  MenuResponseData,
  MenuList,
  RoleResponseData,
  Records,
  RoleData,
} from '@/api/acl/role/type'
import { ElMessage } from 'element-plus'
import useLayoutSettingStore from '@/store/modules/setting'
import useUserStore from '@/store/modules/user'
let currentPage = ref<number>(1)
let pageSize = ref<number>(5)
let total = ref<number>(50)
let roleArr = ref<Records>([])
let roleName = ref<string>('')
let dialogFormValue = ref<boolean>(false)
// 定义数组存储用户权限的数据
let menuArr = ref<MenuList>([])
// 控制抽屉的展开与收起
let drawer = ref<boolean>(false)
// 获取form组件实例
let form = ref()
// 获取tree组件实例
let tree = ref()
// 收集新增岗位的数据
let RoleParams = reactive<RoleData>({
  roleName: '',
})
// 准备一个数组：数组用于存储勾选的节点ID（四级）
let selectArr = ref<number[]>([])
const defaultProps = {
  children: 'children',
  label: 'name',
}
const userStore = useUserStore()
const layoutSettingStore = useLayoutSettingStore()
onMounted(() => {
  getRoleInfo()
})
// 获取角色信息
const getRoleInfo = async (pager = 1) => {
  currentPage.value = pager
  const result: RoleResponseData = await reqAllRoleList(
    currentPage.value,
    pageSize.value,
    roleName.value,
  )
  if (result.code == 200) {
    roleArr.value = result.data.records
    total.value = result.data.total
  } else {
    ElMessage({
      type: 'error',
      message: '获取角色信息失败',
    })
  }
}
// 分页器下拉菜单回调
const handler = () => {
  getRoleInfo()
}
// 搜索回调
const handleSearch = () => {
  getRoleInfo()
}
// 重置按钮的回调
const reset = () => {
  layoutSettingStore.changeRefresh()
}
// 添加职位
const addRole = () => {
  Object.assign(RoleParams, {
    roleName: '',
    id: 0,
  })
  dialogFormValue.value = true
  nextTick(() => {
    form.value.clearValidate()
  })
}
// 更新职位
const updateRole = (row: RoleData) => {
  dialogFormValue.value = true
  Object.assign(RoleParams, row)
  nextTick(() => {
    form.value.clearValidate()
  })
}
const validatorRoleName = (rule: any, value: any, callback: any) => {
  if (value.trim().length >= 2) {
    callback()
  } else {
    callback(new Error('职位名称至少两位'))
  }
}
// 职位校验规则
const rules = {
  roleName: [
    {
      required: true,
      trigger: 'blur',
      validator: validatorRoleName,
    },
  ],
}
// 确定按钮的回调
const save = async () => {
  await form.value.validate()
  //   添加/更新职位请求
  const result: any = await reqAddOrUpdateRole(RoleParams)
  if (result.code == 200) {
    ElMessage({
      type: 'success',
      message: RoleParams.id ? '更新成功' : '添加成功',
    })
    dialogFormValue.value = false
    getRoleInfo(RoleParams.id ? currentPage.value : 1)
  } else {
    ElMessage({
      type: 'success',
      message: RoleParams.id ? '更新失败' : '添加失败',
    })
  }
  dialogFormValue.value = false
}
// 分配权限的回调
const setPermission = async (row: RoleData) => {
  drawer.value = true
  //   收集当前的数据
  Object.assign(RoleParams, row)
  //   根据职位获取权限的数据
  const result: MenuResponseData = await reqAllMenuList(RoleParams.id as number)
  if (result.code == 200) {
    menuArr.value = result.data
    selectArr.value = filterSelectArr(menuArr.value, [])
  }
}
const filterSelectArr = (menuArr: MenuList, initArr: number[]) => {
  menuArr.forEach((item) => {
    if (item.select && item.level == 4) {
      initArr.push(item.id)
    }
    if (item.children && item.children.length > 0) {
      filterSelectArr(item.children, initArr)
    }
  })
  return initArr
}
// 抽屉确定按钮的回调
const selectHandler = async () => {
  const roleId = RoleParams.id
  // 全选的ID
  const arr = tree.value.getCheckedKeys()
  // 半选的ID
  const arr1 = tree.value.getHalfCheckedKeys()
  const permissionId = arr.concat(arr1)
  // 下发权限
  const result: any = await reqSetPermission(roleId as number, permissionId)
  if (result.code == 200) {
    drawer.value = false
    ElMessage({
      type: 'success',
      message: '分配权限成功',
    })
    if (userStore.username == RoleParams.roleName) {
      window.location.reload()
    }
  } else {
    drawer.value = false
    ElMessage({
      type: 'error',
      message: '分配权限失败',
    })
  }
}
// 删除某个角色
const deleteRole = async (id: number) => {
  const result: any = await reqRemoveRole(id)
  if (result.code == 200) {
    ElMessage({
      type: 'success',
      message: '删除成功',
    })
    getRoleInfo(
      currentPage.value > 0 ? currentPage.value : currentPage.value - 1,
    )
  } else {
    ElMessage({
      type: 'error',
      message: '删除失败',
    })
  }
}
</script>

<style scoped>
.form {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
</style>